import  {GoodsRequester} from '@/api/api.js'
import store from '.';
const  goodsRequester = new GoodsRequester();

const state = { 

    //加载分类商品数据
    isLoadingSort : false,
    isLoadingSortNew:false,

    searchKeyWord : '',
    //首页的商品列表
    goodsList:{
        //推荐商品列表
        recommend: [
        /*  
                "userId": 1,
                "goodsId": "1",
                "coverImages": "https://gw.alicdn.com/bao/uploaded/i3/O1CN01HxbAMg1EYkxQEZi8b_!!0-fleamarket.jpg_q50.jpg_.webp",
                "priceDay": 25,
                "priceMonth": 25,
                "title": "阿米洛樱花键盘",
                "merchantName": "Mark",
                "merchantImages": "http://fancyday.fit:9000/leasingplatform/2022/10/15/DefaultHeadPortraits.jpg",
                "credit": 50
            }, */
        
        ],
        
        //摄影列表
        photography:[],

        //书籍
        book:[],

        //汽车
        car:[],

        //数码
        digital:[]

    },

    //搜索商品列表
    searchGoodsList:[

    ],

    //活动商品:
    //二维数组: [类别][具体类别的商品]
    actGoodsList:[

    ]
    

    
}


const actions = {
    //发请求获取推荐商品列表
    getGoodsList({commit,state},{type,keyword,size,isMore}){
        //先看state中是否已经有该类别的商品数据
        //若有，则不发起请求，刷新时再替换
        //若无，发起请求
        if (isMore || state.goodsList[type] && state.goodsList[type].length == 0){    //防止被空值直接覆盖
            if (isMore) state.isLoadingSortNew = true;
            state.isLoadingSort = true;
            if (type == 'recommend' ) keyword = ' ';
            goodsRequester.reqGoodsList(keyword,size).then((res)=>{
                console.log(res);
                commit("GET_GOODS_LIST",{type:type,data:res.data})

            })
        }
    },

    //获取搜索商品列表
    getSearchGoodsList({commit,state},data){
        goodsRequester.reqGoodsList(data,10).then(res=>{
            console.log('搜索结果未：',res);
            commit('GET_SC_LIST',res.data)
        })
    },

    //获取活动商品列表
    getActGoodsList({commit,state},{key,index}){
        goodsRequester.reqSearchGoodsList(key,10).then(res=>{
            console.log(key,'----搜索结果---',res);
            commit('GET_ACT_LIST',{index:index,data:res.data.Goods})
        })
    }
}

const mutations = {
    //获取商品列表
    GET_GOODS_LIST(state,{type,data}){
        data.forEach(good => {
            state.goodsList[type].push(good);
        });
        state.isLoadingSort = false;
        state.isLoadingSortNew =false;
    },

    //更新活动商品列表
    GET_ACT_LIST(state,{index,data}){
        state.actGoodsList[index]=data;
    },


    //更新搜索词
    GET_KEY(state,data){
        state.searchKeyWord = data;
    
    },

    //更新搜索商品列表
    GET_SC_LIST(state,data){
        state.searchGoodsList = data;
    }

}

const getters={
    
    
}

export default {
    namespaced:true,
    state,
    actions,
    mutations,
}